﻿package de.gameduell.framework.game.card {
	import de.gameduell.framework.application.controller.MultiplayerController;
	import de.gameduell.framework.debug.Debug;
	import de.gameduell.framework.modules.IModule;
	import de.gameduell.framework.util.HashMap;
	
	import flash.events.Event;
	import flash.utils.getQualifiedClassName;	

	/**
	 * network controller and event handling for multiplayer card games.
	 * @author ftru
	 */
	public class CardGameController extends MultiplayerController {

		// statics
		private static var instance:CardGameController;
		
		protected var contextMap:HashMap;
						
		/**
		 * Controller is a singlethon, thus has a getInstance function
		 * @return the instance of Controller
		 */
		public static function getInstance():CardGameController {
			if(instance == null) {
				instance = new CardGameController();
			}
			return instance;
		}
		
		public function init(contextMap:HashMap) {
			this.contextMap = contextMap;
		}
		
		/**
		 * required to trace current flow state on incomming events
		 **/
		protected function get flowState():String {
			return getModule("flowManager")["flowState"] as String;
		}

		/**
		 * Contructor
		 * calls the super Construtor and starts initializes and configures the Stopwatch
		 */
		public function CardGameController() {
			super();
		}

		// create a new transition context and dispatch it
		public override function dispatchEvent(event:Event):Boolean {
			Debug.trace("Controller::dispatchEvent() event: " + event.type+ " -> " + getQualifiedClassName(event));
		    
		    // call command mainloop
		    handleEvent(event);
		    
			// dispatch normally
			return super.dispatchEvent(event);		    
		}
		
		// command mainloop
		public function handleEvent(command:Event) {

		    // (maybe) change the current flowState
			getModule("flowManager").handleEvent(command);
		    // (maybe) change the current player
			getModule("playerManager").handleEvent(command);
		    // (maybe) change the current team
			getModule("teamManager").handleEvent(command);
		    
		    // work on new flowState, player or team but can access the old state
		    getModule("stackManager").handleEvent(command);
		    getModule("popupManager").handleEvent(command);
		    getModule("chatManager").handleEvent(command);
		    getModule("stopWatchManager").handleEvent(command);
			getModule("threadPoolManager").handleEvent(command);
		}	
		
		public function getModule(moduleId:String):IModule {
			return IModule(contextMap.getValue(moduleId));
		}
		
		
	}
}
